using System;
using PrimeTween;
using UnityEngine;
using UnityEngine.UI;

namespace UI
{
    public class SceneTransition : MonoBehaviour
    {
        private Image _image;

        [SerializeField]
        private bool transitOnStart = false;

        [SerializeField]
        private float transitionTime = 1f;

        
        // Start is called before the first frame update
        private void Start()
        {
            _image = GetComponent<Image>();

            if (transitOnStart)
            {
                SetAlpha(1f);
                FadeIn();
            }
        }

        public void FadeIn(Action actionOnFaded = null) => DoFade(0f, actionOnFaded);

        public void FadeOut(Action actionOnFaded = null) => DoFade(1f, actionOnFaded);

        private void DoFade(float targetAlpha, Action actionOnFaded) => 
            Tween.Alpha(_image, targetAlpha, transitionTime, useUnscaledTime: true).OnComplete(() => actionOnFaded?.Invoke());

        private void SetAlpha(float alpha)
        {
            Color color = _image.color;
            color.a = alpha;
            _image.color = color;
        }
    }
}